package com.example.core.hql.query;

import com.example.core.hql.HQLInfo;
import com.example.shiro.utils.UserAuthInfo;
import com.example.shiro.utils.UserUtils;
import com.example.sys.authority.service.SysAuthorityService;
import com.example.sys.module.mode.SysModuleInfo;
import com.example.sys.module.service.SysModuleService;
import com.example.sys.module.service.impl.SysModuleViewRoleServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SysReaderHQlPart implements IQueryHQLPart {

    @Resource
    private SysModuleService sysModuleService;

    @Resource
    private SysAuthorityService sysAuthorityService;

    @Override
    public HQLInfo buildQueryHQL(HQLInfo hqlInfo) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        SysModuleInfo sysModuleInfo = this.sysModuleService.getSysModuleInfoBySimpleName(hqlInfo.getModelName());
        if (subject.isAuthenticated()) {
            String moduleViewRole = sysModuleInfo.getBaseRole() + SysModuleViewRoleServiceImpl.VIEW;
            if (UserUtils.getUser().getAuthRoleAliases().contains(moduleViewRole)) {
                return hqlInfo;
            } else {
                return this.sysAuthorityService.buildQueryHQL((UserAuthInfo) subject.getPrincipal(), hqlInfo);
            }
        }
        return hqlInfo;
    }
}
